<!-- 新增分区 -->
<template>
  <div>
    <el-dialog title="添加" :visible.sync="dialogShow" width="1100px" :close-on-click-modal="false" :close-on-press-escape="false">
      <form-common :filed-list="contractLeaseList" ref="infoForm" :formObj="model" @selectChange="selectChange" @rightBtnFn="rightBtnFn"></form-common>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false" class="el-button-reset">取 消</el-button>
        <el-button type="primary" @click="confirmFn">确 认</el-button>
      </div>
    </el-dialog>
    <equipment-tree ref="equipment" :contractType="contractType" @setEquipment="setEquipment" :optionMap="optionMap"></equipment-tree>
    <facility-tree ref="facility" :contractType="contractType" @setFacility="setFacility" :optionMap="optionMap"></facility-tree>
  </div>
</template>
<script>
  import formCommon from '@g/components/form/formCommon.vue';
  import equipmentTree from './equipmentTree.vue';
  import facilityTree from './facilityTree.vue';
  import { contractPayList } from '../form.js';
  import { guid, setFiledVal } from '@/common/js/utils';
  import { apiPaysonList } from '../../../../api/contract';
  import Bus from '@js/bus.js';

  export default {
    props: {
      contractType: {
        type: String,
        default: '',
      },
      tableList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      //基本信息中的项目key 合同开始时间 结束时间
      relevanceParam: {
        type: Object,
        default: () => {
          return {};
        },
      },
      //设备 设施
      optionMap: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },

    data() {
      return {
        dialogShow: false,
        contractLeaseList: contractPayList,
        model: {},
      };
    },

    watch: {
      tableList: {
        deep: true,
        handler(val) {
          this.setAllowRentSapceList();
        },
      },
    },

    methods: {
      //添加时初始化
      async init(type) {
        this.dialogShow = true;
        this.model = {};
        if (type == 'add') {
          this.initFiledVal();
          this.setAllowRentSapceList();
        }
        await this.$nextTick(() => {});
        this.$refs.infoForm.clearValidateForm();
      },

      //保存
      confirmFn() {
        let model = this.$refs.infoForm.validateForm(); //基本信息
        if (!model) return;

        let assetObj = this.setChargeItemName(model.chargeItemKey);
        model.chargeItemName = assetObj.chargeItemName;

        this.dialogShow = false;
        this.$emit('confirmAddItem', model);
      },

      //编辑营
      editItem() {
        this.setAllowRentSapceList();
        this.unshiftRentSapceList();
      },

      //初始化表单字段为空
      initFiledVal() {
        this.contractLeaseList.forEach(item => {
          item.bindFieldVal = '';
        });
      },

      //可租空间不可重复选择
      setAllowRentSapceList() {
        let choseList = [];
        this.tableList.forEach(item => {
          choseList.push(item.chargeItemKey);
        });
        this.contractLeaseList.forEach(item => {
          if (item.bindFieldName == 'chargeItemKey') {
            item.optionList.forEach(option => {
              if (choseList.indexOf(option.primaryKey) > -1) {
                option.ifCanChecked = false;
              } else {
                option.ifCanChecked = true;
              }
            });
          }
        });
      },

      //可租空间编辑时 要手动把之前 选过的option 的 ifCanChecked字段置为true让其显示
      unshiftRentSapceList() {
        this.contractLeaseList.forEach(item => {
          if (item.bindFieldName == 'chargeItemKey') {
            item.optionList.forEach(option => {
              if (option.primaryKey == this.model.chargeItemKey) {
                option.ifCanChecked = true;
              }
            });
          }
        });
      },

      //选择事项把name传给后台
      setChargeItemName(chargeItemKey) {
        let assetObj = {};
        this.contractLeaseList.forEach(item => {
          if (item.bindFieldName == 'chargeItemKey') {
            assetObj = item.optionList.find(option => option.primaryKey == chargeItemKey);
          }
        });
        return {
          chargeItemName: assetObj ? assetObj.chargeItemAliasName : "",
        };
      },

      //表单事件
      selectChange(data) {
        // 判断时间
        if (data.filedName == 'rentStartDate' || data.filedName == 'rentEndDate') {
          let timestamp = data.model.rentEndDate - data.model.rentStartDate;
          if (timestamp < 0) {
            if (data.filedName == 'rentEndDate') {
              this.$message.warning('结束时间应大于开始时间');
              data.model.rentEndDate = '';
            }
            if (data.filedName == 'rentStartDate' && data.model.rentEndDate) {
              this.$message.warning('结束时间应大于开始时间');
              data.model.rentEndDate = '';
            }
            return;
          }
        }
      },

      //表单事件
      rightBtnFn(data) {
        if (data.filedName == 'assetName') {
          console.log(data.model);
          let tags = [];
          let keyList = data.model.assetKey ? data.model.assetKey.split(',') : [];
          let txtList = data.model.assetName ? data.model.assetName.split(',') : [];
          keyList.forEach((item, index) => {
            tags.push({
              key: keyList[index],
              name: txtList[index],
            });
          });
          console.log(tags)
          this.$refs.equipment.init(tags);
        }
        if (data.filedName == 'stationName') {
          let tags = [];
          let keyList = data.model.stationKey ? data.model.stationKey.split(',') : [];
          let txtList = data.model.stationName ? data.model.stationName.split(',') : [];
          keyList.forEach((item, index) => {
            tags.push({
              key: keyList[index],
              name: txtList[index],
            });
          });
          this.$refs.facility.init(tags);
        }
      },

      //设备赋值
      setEquipment(tags) {
        let keys = '';
        let names = '';
        tags.forEach(item => {
          keys += item.key + ',';
          names += item.name + ',';
        });
        names = names.substr(0, names.length - 1);
        keys = keys.substr(0, keys.length - 1);
        this.$refs.infoForm.setFiledSource('assetKey', keys);
        this.$refs.infoForm.setFiledSource('assetName', names);
      },

      //设施赋值
      setFacility(tags) {
        let keys = '';
        let names = '';
        tags.forEach(item => {
          keys += item.key + ',';
          names += item.name + ',';
        });
        names = names.substr(0, names.length - 1);
        keys = keys.substr(0, keys.length - 1);
        this.$refs.infoForm.setFiledSource('stationKey', keys);
        this.$refs.infoForm.setFiledSource('stationName', names);
      },

      //接受兄弟传值
      initBus() {
        Bus.$on('costItem', async data => {
          console.log(data);
          await this.init();
          this.model = data;
          this.editItem();
        });
      },

      //事项类型
      async getChargeItemList(filedName) {
        let res = await apiPaysonList({ contractType: this.contractType });
        this.contractLeaseList.forEach(item => {
          if (item.bindFieldName == 'chargeItemKey') {
            item.optionList = res.rows || [];
          }
        });
        console.log(this.contractLeaseList);
      },
    },

    created() {
      this.initBus();
      this.getChargeItemList();
    },

    components: { formCommon, equipmentTree, facilityTree },
  };
</script>
<style lang="scss" scoped>
  .delete-btn {
    position: absolute;
    top: 0;
    right: 0;
  }
  ::v-deep .el-button--text {
    font-size: 18px;
  }
</style>
